package uk.co.revisual.core
{
	import flash.net.URLRequest;
	
	import mx.events.FlexEvent;
	import mx.modules.Module;

	public class CoreModule extends Module
	{
		private static const MULTICORE_KEY_ERROR:String = "the multicore key property can only be set once";
		private static const NULL_START_UP_CLASS:String = "no start up command class has been set";
		private var _multicoreKey:String;
		private var _settingsURL:URLRequest;
		private var _startUpCmdClass:Class;
		private var _stageMediatorClass:Class;
		
		public function CoreModule()
		{
			addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			addEventListener(FlexEvent.APPLICATION_COMPLETE, onApplicationComplete);
		}
		
		public function set startUpCmdClass(c:Class):void{
			_startUpCmdClass = c;
		}
		
		public function set stageMediatorClass(c:Class):void{
			_stageMediatorClass = c;
		}
		
		public function get multicoreKey():String{
			return _multicoreKey;
		}
		
		public function set multicoreKey(key:String):void{
			if(!_multicoreKey){
				_multicoreKey = key;
			}else{
				throw new Error (MULTICORE_KEY_ERROR);
			}
		}
		
		public function get settingsURL():URLRequest{
			return _settingsURL;
		}
		
		public function initiate():void{
			//_settingsURL = url;
			if(!_startUpCmdClass)throw new Error( NULL_START_UP_CLASS );
			getCore().startup( this, _startUpCmdClass );
			
		}
		protected function onCreationComplete(event:FlexEvent):void{
			removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			initiate()
		}
		
		protected function onApplicationComplete(event:FlexEvent):void{
			removeEventListener(FlexEvent.APPLICATION_COMPLETE, onApplicationComplete);
			if(_stageMediatorClass)getCore().injectStage( this.stage, _stageMediatorClass );
		}
		
		private function getCore():CoreFacade{
			return CoreFacade( CoreFacade.getInstance( _multicoreKey ) );
		}
		
		
	}
}